package logic

import (
	"context"
	"errors"
	"user_srv/models"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *user.UpdatePasswordRequest) (*user.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var u models.User
	u.ID = uint(in.UserId)
	err := u.FinduserId()
	if err != nil {
		logx.Error("查询用户ID失败", err)
		return nil, err
	}

	if u.Password != in.Password {
		logx.Error("原密码输入错误，禁止修改")
		return nil, errors.New("原密码输入错误，禁止修改")
	}

	if u.Password == in.NewPassword {
		logx.Error("新密码与原密码一致，禁止修改")
		return nil, errors.New("新密码与原密码一致，禁止修改")
	}

	if in.NewPassword != in.AckPassword {
		logx.Error("两次密码不一致，禁止修改")
		return nil, errors.New("两次密码不一致，禁止修改")
	}

	u.Password = in.NewPassword
	err = u.UpdatePassword()
	if err != nil {
		logx.Error("修改密码失败", err)
		return nil, errors.New("修改密码失败")
	}

	return &user.UpdatePasswordResponse{
		UserId: int64(u.ID),
	}, nil
}
